package com.css.zfzx.sjcj.modules.hddccjfilemanage.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.org.dept.repository.entity.DeptEntity;
import com.css.bpm.platform.org.division.repository.DivisionNativeRepository;
import com.css.bpm.platform.org.division.repository.DivisionRepository;
import com.css.bpm.platform.org.division.repository.entity.DivisionEntity;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.division.service.MyDivisionService;
import com.css.zfzx.sjcj.common.utils.CheckObjFields;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.common.vo.DivisionVo;
import com.css.zfzx.sjcj.modules.hddccjfilemanage.repository.HddcFileManageNativeRepository;
import com.css.zfzx.sjcj.modules.hddccjfilemanage.repository.HddcFileManageRepository;
import com.css.zfzx.sjcj.modules.hddccjfilemanage.repository.entity.HddcFileManageEntity;
import com.css.zfzx.sjcj.modules.hddccjfilemanage.service.HddcFileManageService;
import com.css.zfzx.sjcj.modules.hddccjfilemanage.viewobjects.HddcFileManageQueryParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

/**
 * @author zyb
 * @date 2020-12-10
 */
@Slf4j
@Service
@PropertySource(value = "classpath:platform-config.yml")
public class HddcFileManageServiceImpl implements HddcFileManageService {

    @Value("${file-upload.attachment-directory.config.defaultDirectory.fileDirectory}")
    private String localPath;
	@Autowired
    private HddcFileManageRepository hddcFileManageRepository;
    @Autowired
    private HddcFileManageNativeRepository hddcFileManageNativeRepository;
    @Autowired
    private MyDivisionService myDivisionService;

    @Override
    public JSONObject queryHddcFileManages(HddcFileManageQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        if (!PlatformObjectUtils.isEmpty(sort) && sort.length() > 0) {
            sort = CheckObjFields.propertyChange(sort);
        }
        Page<HddcFileManageEntity> hddcFileManagePage = this.hddcFileManageNativeRepository.queryHddcFileManages(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcFileManagePage);
        return jsonObject;
    }


    @Override
    public HddcFileManageEntity getHddcFileManage(String id) {
        HddcFileManageEntity hddcFileManage = this.hddcFileManageRepository.findById(id).orElse(null);
         return hddcFileManage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcFileManageEntity saveHddcFileManage(HddcFileManageEntity hddcFileManage) {
        String uuid = UUIDGenerator.getUUID();
        hddcFileManage.setUuid(uuid);
        String usersId=PlatformSessionUtils.getUserId();
        if(StringUtils.isNotEmpty(usersId)){
            hddcFileManage.setCreateUser(usersId);
        }
        DivisionVo divisionVo = myDivisionService.getDivision(hddcFileManage.getCreateUser());
        if (StringUtils.isNotEmpty(divisionVo.getProvinceName())) {
            hddcFileManage.setProvince(divisionVo.getProvinceName());
        }
        if (StringUtils.isNotEmpty(divisionVo.getCityName())) {
            hddcFileManage.setCity(divisionVo.getCityName());
        }
        if (StringUtils.isNotEmpty(divisionVo.getAreaName())) {
            hddcFileManage.setArea(divisionVo.getAreaName());
        }
        hddcFileManage.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcFileManage.setIsValid("1");
        hddcFileManage.setQualityinspectionStatus("0");
        hddcFileManage.setExtends10("1");
        this.hddcFileManageRepository.save(hddcFileManage);
        return hddcFileManage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcFileManageEntity updateHddcFileManage(HddcFileManageEntity hddcFileManage) {
        HddcFileManageEntity entity = hddcFileManageRepository.findById(hddcFileManage.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcFileManage);
        hddcFileManage.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcFileManage.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcFileManageRepository.save(hddcFileManage);
        return hddcFileManage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcFileManages(List<String> ids) {
        List<HddcFileManageEntity> hddcFileManageList = this.hddcFileManageRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcFileManageList) && hddcFileManageList.size() > 0) {
            for(HddcFileManageEntity hddcFileManage : hddcFileManageList) {
                hddcFileManage.setIsValid("0");
                hddcFileManage.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcFileManage.setUpdateTime(new Date());
                this.hddcFileManageRepository.save(hddcFileManage);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    private void addOrUpdateHddcFileManage(String name,String filenumber,String authors) {
        HddcFileManageEntity hddcFileManageEntity = new HddcFileManageEntity();
        hddcFileManageEntity.setFileName(name);
        hddcFileManageEntity.setFileId(filenumber);
        hddcFileManageEntity.setExtends1(authors);
        this.saveHddcFileManage(hddcFileManageEntity);
        /*HddcFileManageQueryParams params = new HddcFileManageQueryParams();
        params.setFileName(name);
        params.setFileId(filenumber);

        Page<HddcFileManageEntity> hddcFileManagePage = this.hddcFileManageNativeRepository.queryHddcFileManages(params, 1, 10);

        HddcFileManageEntity hddcFileManageEntity = new HddcFileManageEntity();
        hddcFileManageEntity.setFileName(name);
        hddcFileManageEntity.setFileId(filenumber);

        //update add
        if(hddcFileManagePage.getContent().size() > 0) {
            hddcFileManageEntity = hddcFileManagePage.getContent().get(0);
            this.updateHddcFileManage(hddcFileManageEntity);
        } else {
            this.saveHddcFileManage(hddcFileManageEntity);
        }*/
    }
    @Override
    public int upload(MultipartFile file,String filenumber,String authors) {
        List<HddcFileManageEntity> hddcFileManageEntity=hddcFileManageRepository.findbyId(filenumber);
        int count=0;
        if (!hddcFileManageEntity.isEmpty()&&hddcFileManageEntity.size()!=0){
            return count;//该编号已存在
        }
        try {
            String path = localPath + File.separator+"file";//上传的路径
            File dir = new File(path);
            if (!dir.exists()) {
                //路径不存在就创建路径
                dir.mkdirs();
            }
            String fileName = file.getOriginalFilename();
            File file1 = new File(path, fileName);
            file.transferTo(file1);
            addOrUpdateHddcFileManage(fileName,filenumber,authors);
            //addOrUpdateHddcFileManage(fileName.substring(0,fileName.lastIndexOf('.')),filenumber);
            count=2;//上传成功
        } catch (IOException e) {
            //throw new Exception(e.getMessage());
            log.error(e.getMessage());
            count=1;//上传失败
        }
        return count;
    }

    @Override
    public void download(String name, HttpServletResponse response) {
        try {
            String path = localPath +File.separator+"file";//文件的下载地址
            String fullName = name;
            //设置响应头
            response.reset();//设置页面不缓存
            response.setCharacterEncoding("UTF-8");//字符集编码
            response.setContentType("multipart/form-data");//二进制传输文件
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fullName, "UTF-8"));//设置响应头
            File file = new File(path, fullName);
            //输入流
            FileInputStream inputStream = new FileInputStream(file);
            //输出流
            ServletOutputStream outputStream = response.getOutputStream();

            byte[] bytes = new byte[10240000];
            int index = 0;
            while ((index = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, index);
                outputStream.flush();
            }
            outputStream.close();
            inputStream.close();
        } catch (Exception e) {

        }
    }

    /**
     * 逻辑删除-根据项目id删除数据
     * @param projectIds
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcFileManageEntity> hddcFileManageList = this.hddcFileManageRepository.queryHddcFileManagesByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcFileManageList) && hddcFileManageList.size() > 0) {
            for(HddcFileManageEntity hddcFileManage : hddcFileManageList) {
                hddcFileManage.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcFileManage.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcFileManage.setIsValid("0");
                this.hddcFileManageRepository.save(hddcFileManage);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     * @param taskIds
     */
    @Override
    public void deleteByTaskId(List<String> taskIds) {
        List<HddcFileManageEntity> hddcFileManageList = this.hddcFileManageRepository.queryHddcFileManagesByTaskId(taskIds);
        if(!PlatformObjectUtils.isEmpty(hddcFileManageList) && hddcFileManageList.size() > 0) {
            for(HddcFileManageEntity hddcFileManage : hddcFileManageList) {
                hddcFileManage.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcFileManage.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcFileManage.setIsValid("0");
                this.hddcFileManageRepository.save(hddcFileManage);
            }
        }

    }

}
